<?php

Yii::import('common.models.page.*');
Yii::import('common.models.ad.*');

class FlashAdsController extends Controller {

    public $activeMenu = 'cms';

    public function actionCreate() {

	$model = new FlashAds;
	if (isset($_POST['FlashAds'])) {

	    $model->attributes = $_POST['FlashAds'];

	    //check photo

	    if (($imageUploadFile = CUploadedFile::getInstance($model, 'photo'))) { // only do if file is really uploaded
		$imageFileName = time() . $imageUploadFile->name;

		$imageUploadFile->saveAs(UPLOAD_PATH . $imageFileName);

		//delete previous image

		if ($model->image != '')
		    @unlink(UPLOAD_PATH . $model->image);

		$model->image = $imageFileName;
	    }

	    if ($model->save()) {
		Yii::app()->user->setFlash('success', 'The ads has been created');
		//redirect to update
		$this->redirect(array('update', 'id' => $model->block_id));
	    } else {
		Yii::app()->user->setFlash('error', 'Sorry, please try again');
	    }
	}

	$this->render('create', array(
	    'model' => $model
	));
    }

    public function actionUpdate($id) {

	$model = $this->_loadModel($id);



	if (isset($_POST['FlashAds'])) {

	    $model->attributes = $_POST['FlashAds'];

	    $model->isNewRecord = FALSE;



	    //check photo

	    if (($imageUploadFile = CUploadedFile::getInstance($model, 'photo'))) { // only do if file is really uploaded
		$imageFileName = time() . $imageUploadFile->name;

		$imageUploadFile->saveAs(UPLOAD_PATH . $imageFileName);

		//delete previous image
		if ($model->image != '')
		    @unlink(UPLOAD_PATH . $model->image);
		$model->image = $imageFileName;
	    }



	    if ($model->save()) {
		Yii::app()->user->setFlash('success', 'The ads has been updated');
	    } else {
		Yii::app()->user->setFlash('error', 'Sorry, please try again');
	    }
	}

	$this->render('update', array(
	    'model' => $model
	));
    }

    /**
     * delete flash ads
     * @param type $id
     */
    public function actionDelete($id) {
	if (!Yii::app()->request->isPostRequest)
	    throw new CHttpException(404, 'The page you has been requested not exists');

	$model = FlashAds::model()->findByPk($id);
	$model->isNewRecord = FALSE;

	if (!$model) {
	    throw new CHttpException(404, 'The page you has been requested not exists');
	}

	if ($model->image != '')
	    @unlink(UPLOAD_PATH . $model->image);

	$model->delete();
    }

    public function actionIndex() {
	$model = new FlashAds('search');
	if (isset($_GET['FlashAds']))
	    $model->attributes = $_GET['FlashAds'];

	$this->render('index', array(
	    'model' => $model
	));
    }

    private function _loadModel($id) {
	$model = FlashAds::model()->findByPk($id);
	if (!$model)
	    throw new CHttpException(404, 'The page you has been requested not exists');
	return $model;
    }

}
